<template>
	<view class="">
		<view class="e-p-t-26 e-m-b-20">
			<view class="e-flex e-m-b-14 e-font-28" v-if="orderVos.orderMoney >= gFig?.orderStartPrice">
				<text class="e-flex-1 c-333">{{$t('classify.配送服务')}}</text>
				<view class="e-flex" v-if="orderDeliveryfee">
					<text class="low-throw c-secondary e-m-r-10"
						v-if="orderVos.orderMoney >= gFig.fullDiscountPrice">{{$unitEn}}{{orderDeliveryfee + gFig.deliveryDeratePrice}}</text>
					<text class="c-333 fw-600">{{$unitEn}}{{orderDeliveryfee}}</text>
				</view>
				<view class="" v-else>
					<text>{{$t('classify.免配送费')}}</text>
				</view>
			</view>
			<view class="e-font-24 c-secondary" v-if="gFig.fullDiscountPrice">
				<text class="e-p-r-8">{{$t('classify.订单满')}}</text>
				<text class="e-p-r-8">{{$unitEn}}{{gFig.fullDiscountPrice}}</text>
				<text class="e-p-r-8">{{$t('classify.减配送费')}}</text>
				<text> {{$unitEn}}{{gFig.deliveryDeratePrice}}</text>
			</view>
		</view>
		<view class="e-flex e-p-t-20 bg-white">
			<view class="e-flex-1 c-333 e-font-24 fw-600">
				{{$t('classify.配送时间')}}
			</view>
			<view class="e-flex" @tap="show = true">
				<view class="e-m-r-20 c-primary">
					{{selectTime}} {{$t('cart.送达')}}
				</view>
				<app-image src="arrow_right.png" :size="['36rpx']" />
			</view>
		</view>


		<!-- 弹窗 -->
		<e-popup :show="show" round="20rpx" @close="close">
			<view class="nearby-store-address__popup">
				<view class="e-p-t-22 e-p-b-24 e-rela e-flex-xy-center">
					<text class="e-font-32 fw-500">{{ $t('cart.选择预计送达时间') }}</text>
					<image src="/pages/systemPay/static/close.png" class="nearby-store-address__popup-icon img-28" @tap="close">
					</image>
				</view>
				<view class="nearby-store-address__popup-body e-flex e-flex-items-start">
					<view class="nearby-store-address__popup-day">
						<view class="e-flex-xy-center" v-for="(item,index) in dateList" :key="item.id"
							:class="{ 'bg-white': dateIndex === index }" @tap="setDayType(index)">
							{{item.name}}
						</view>

					</view>
					<view class="nearby-store-address__popup-time e-flex-1 bg-white">
						<scroll-view scroll-y="true" v-if="dateList[dateIndex]">
							<view class="">
								<view class="nearby-store-address__popup-time__item e-flex e-flex-between"
									v-for="(item, index) in dateList[dateIndex].value" :key="index"
									@tap="timeIndex = index">
									<template v-if="item">
										<text v-if="receivingType === 3 && !index && checkTime(item)"
											:class="{ 'c-primary': timeIndex === index }">{{$t('classify.尽快送达')}}（{{$t('classify.大约')}}{{item}}）</text>
										<text v-else :class="{ 'c-primary': timeIndex === index }">{{ item }}</text>
										<image src="/pages/systemPay/static/success.png" v-show="timeIndex === index"></image>
									</template>
								</view>
							</view>
						</scroll-view>
					</view>
				</view>
			</view>
		</e-popup>
	</view>
</template>
<script lang="ts">
	import {
		defineComponent
	} from 'vue'
	export default defineComponent({
		// #ifdef MP-WEIXIN
		// 将自定义节点设置成虚拟的，更加接近Vue组件的表现
		options: {
			virtualHost: true
		},
		// #endif
	})
</script>
<script setup lang="ts">
	import { ref, computed, watch } from 'vue'
	import type { OrderGoods } from '@/common/request/api'
	import { useCurrentInstance } from '@/common/hooks'
	import { timeFormat,padZero } from '@/common/utils'

	const props = defineProps<{
		orderVos : OrderGoods,
		orderDeliveryfee : number,
		deliveryTimes : Array<{
			selectTime : string
			deliveryTimes : string
			storeId : string
		}>,
		receivingType : number
	}>()

	const emits = defineEmits(['setDeliveryTime'])

	const ctx = useCurrentInstance()

	const timeIndex = ref(0)
	const show = ref(false)
	const dateList = ref<Array<{
		id : number
		value : string[]
		formmatDate : string
		name : string
	}>>([])
	const dateIndex = ref(0)
	const selectTime = ref('')
	type GoodsFig = {
		fullDiscountPrice : number
		daysInAdvance : number
		lagTime : number
		sunTimeSlots : string
		monTimeSlots : string
		tueTimeSlots : string
		wedTimeSlots : string
		thuTimeSlots : string
		friTimeSlots : string
		satTimeSlots : string
		deliveryType : number
		deliveryDeratePrice : number
		orderStartPrice:number
	}
	const gFig = computed<GoodsFig | null>(() => {
		if (props.orderVos && props.orderVos.fig) {
			return JSON.parse(props.orderVos.fig)
		}
		return null
	})


	const checkTime = (val : string) => {
		const arr = val.split('-')
		return arr.length < 2
	}
	const setDayType = (index : number) => {
		dateIndex.value = index
	}
	const close = () => {
		show.value = false
		const time = dateList.value[dateIndex.value].value[timeIndex.value]
		const formmatDate = dateList.value[dateIndex.value].formmatDate
		const params = {
			deliveryTimes: formmatDate + " " + time,
			storeId: props.orderVos.storeId,
			selectTime: time
		}
		emits('setDeliveryTime', params)
	}
	const initDate = (obj : GoodsFig) => {
		dateList.value = []
		let num = obj.daysInAdvance ? obj.daysInAdvance : 0

		for (let i = 0; i <= num; i++) {
			let name
			if (i === 0) {
				name = `${ctx.$t('cart.今天')}(${getWeek()})`
			} else if (i === 1) {
				name = `${ctx.$t('cart.明天')}(${getWeek(1)})`
			} else {
				name = `${getDateStr(i)}(${getWeek(i)})`
			}
			let weekIndex = getWeekIndex(i)
			const timeArr : string[] = []
			let arr : string[] = []
			
			// 延后时间
			const lagTime = obj.lagTime || 0
			
			switch (weekIndex) {
				case 0:
					arr = obj.sunTimeSlots.split(',')
					break
				case 1:
					arr = obj.monTimeSlots.split(',')
					break
				case 2:
					arr = obj.tueTimeSlots.split(',')
					break
				case 3:
					arr = obj.wedTimeSlots.split(',')
					break
				case 4:
					arr = obj.thuTimeSlots.split(',')
					break
				case 5:
					arr = obj.friTimeSlots.split(',')
					break
				case 6:
					arr = obj.satTimeSlots.split(',')
					break
			}
			arr.forEach(item => {
				if (!i) {
					const _t = item.split('-')
					const now = new Date()
					const y = now.getFullYear()
					const mm = now.getMonth() + 1
					const day = now.getDate()
					const nowTime = new Date(now.setMinutes(now.getMinutes() + lagTime))
					if (obj.deliveryType === 1) {
						//闪送：当前时间加上延后时间在闪送时间内，则该闪送时间仍旧有效并有一个尽快送达时间
						if (nowTime > new Date(`${y}-${mm}-${day} ${_t[1]}`)) return
						if (nowTime > new Date(`${y}-${mm}-${day} ${_t[0]}`) && nowTime <= new Date(
							`${y}-${mm}-${day} ${_t[1]}`)) {
							let hour = padZero(nowTime.getHours())
							let minute = padZero(nowTime.getMinutes())
							timeArr.push(`${hour}:${minute}`)
							timeArr.push(item)
							return
						}
					} else {
						// 配送：当前时间加上延后时间在配送时间内则跳过该配送时间
						if (nowTime > new Date(`${y}-${mm}-${day} ${_t[0]}`)) return
					}
					timeArr.push(item)
				} else {
					timeArr.push(item)
				}
			})
			dateList.value.push({
				id: new Date().getTime() + Math.random(),
				value: timeArr,
				formmatDate: getFormmatDate(i),
				name
			})
		}
		// 过滤掉没有时间的日期
		const notValueIndex = dateList.value.filter(item => !item.value.length || !item.value[0])
		if (notValueIndex) {
			notValueIndex.forEach(() => {
				dateList.value.splice(dateList.value.findIndex(index => !index.value.length || !index.value[
					0]), 1)
			})
		}

		if (dateList.value?.length) {
			// 初始化赋值
			const formmatDate = dateList.value[dateIndex.value].formmatDate
			const time = dateList.value[0].value[0]
			const params = {
				deliveryTimes: formmatDate + " " + time,
				storeId: props.orderVos?.storeId,
				selectTime: time
			}
			emits('setDeliveryTime', params)
		}

	}
	const getFormmatDate = (AddDayCount = 0) => {
		const dd = new Date();
		dd.setDate(dd.getDate() + AddDayCount);
		return timeFormat(dd, 'yyyy-mm-dd')

	}
	const getDateStr = (AddDayCount = 0) => {
		const dd = new Date();
		dd.setDate(dd.getDate() + AddDayCount);

		return timeFormat(dd, 'mm/dd')

	}
	const getWeek = (AddDayCount = 0) => {
		const dd = new Date();
		dd.setDate(dd.getDate() + AddDayCount);
		const index = dd.getDay()
		const weeks = [ctx.$t('cart.周日'), ctx.$t('cart.周一'), ctx.$t('cart.周二'), ctx.$t('cart.周三'), ctx.$t(
			'cart.周四'), ctx.$t('cart.周五'), ctx.$t('cart.周六')]
		return weeks[index]
	}
	const getWeekIndex = (AddDayCount = 0) => {
		const dd = new Date();
		dd.setDate(dd.getDate() + AddDayCount);
		const index = dd.getDay()
		return index
	}


	watch(gFig, (v) => {
		if (v) {
			dateIndex.value = 0
			initDate(v)
		}

	}, {
		immediate: true,
		deep: true
	})

	watch(() => props.deliveryTimes, (val) => {
		if (val) {
			val.some(item => {
				if (item.storeId === props.orderVos.storeId) {
					selectTime.value = item.deliveryTimes
					return true
				}
			})
		}
	}, {
		immediate: true,
		deep: true
	})
</script>

<style lang="scss" scoped>
	.nearby-store-address {
		padding: 32rpx 20rpx 22rpx 20rpx;

		&__icon {
			padding: 0 4rpx;
		}

		&__time {
			padding-right: 30rpx;
			position: relative;

			&::after {
				content: '';
				height: calc(100% - 20rpx);
				width: 2rpx;
				background-color: #e6e6e6;
				position: absolute;
				right: 0;
				top: 10rpx;
			}
		}

		&__add {
			overflow: hidden;
			padding-left: 28rpx;
		}

		&__popup {
			height: 60vh;

			&-icon {
				position: absolute;
				right: 20rpx;
				top: 32rpx;
			}

			&-body {
				border-top: 2rpx solid #e2e2e2;
				background: #f7f7f7;
			}

			&-day {
				flex: 0 0 256rpx;
				height: calc(60vh - 50px);
				overflow-y: auto;

				>view {
					height: 94rpx;
				}
			}

			&-time {
				scroll-view {
					height: calc(60vh - 50px);
				}

				&__item {
					padding: 0 20rpx 0 22rpx;
					height: 94rpx;

					image {
						width: 22rpx;
						height: 18rpx;
					}
				}
			}
		}
	}

	.low-throw {
		text-decoration: line-through;
	}
</style>